<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>订单管理 - 助农购物网站</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .order-card {
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        .order-status {
            font-weight: bold;
        }
        .status-pending { color: #ffc107; }
        .status-paid { color: #0d6efd; }
        .status-shipped { color: #198754; }
        .status-completed { color: #6c757d; }
        .status-cancelled { color: #dc3545; }
        .image-preview-container {
            position: relative;
            display: inline-block;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .image-preview-container img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
        }
        .image-preview-container .delete-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: #dc3545;
            color: white;
            border: 2px solid white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            line-height: 1;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .image-preview-container .delete-btn:hover {
            background-color: #c82333;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container mt-4">
        <h2 class="mb-4">订单管理</h2>
        
        <c:if test="${param.message != null}">
            <div class="alert alert-success">${param.message}</div>
        </c:if>
        
        <c:if test="${param.error != null}">
            <div class="alert alert-danger">${param.error}</div>
        </c:if>
        
        <c:if test="${orders != null && !empty orders}">
            <c:forEach var="order" items="${orders}">
                <div class="card order-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <strong>订单编号：</strong>${order.orderNo}
                            <br>
                            <small class="text-muted">下单时间：<fmt:formatDate value="${order.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></small>
                        </div>
                        <div>
                            <c:choose>
                                <c:when test="${order.status == 0}">
                                    <span class="order-status status-pending">待付款</span>
                                </c:when>
                                <c:when test="${order.status == 1}">
                                    <span class="order-status status-paid">待发货</span>
                                </c:when>
                                <c:when test="${order.status == 2}">
                                    <span class="order-status status-shipped">待收货</span>
                                </c:when>
                                <c:when test="${order.status == 3}">
                                    <span class="order-status status-completed">已完成</span>
                                </c:when>
                                <c:when test="${order.status == 4}">
                                    <span class="order-status status-cancelled">已取消</span>
                                </c:when>
                                <c:when test="${order.status == 5}">
                                    <span class="order-status status-after-sale">售后中</span>
                                </c:when>
                                <c:otherwise>
                                    <span class="order-status">未知状态</span>
                                </c:otherwise>
                            </c:choose>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <p><strong>收货地址：</strong>${order.deliveryAddress}</p>
                                <p><strong>收货人：</strong>${order.receiverName} ${order.receiverPhone}</p>
                                <c:if test="${order.logisticsCompany != null}">
                                    <p><strong>物流信息：</strong>${order.logisticsCompany} ${order.logisticsNo}</p>
                                </c:if>
                            </div>
                            <div class="col-md-4 text-end">
                                <h4 class="text-danger">¥${order.totalAmount}</h4>
                                <div class="mt-2">
                                    <c:if test="${order.status == 0}">
                                        <a href="${pageContext.request.contextPath}/client/order?action=pay&orderId=${order.orderId}" 
                                           class="btn btn-primary btn-sm">立即付款</a>
                                        <a href="${pageContext.request.contextPath}/client/order?action=cancel&orderId=${order.orderId}" 
                                           class="btn btn-secondary btn-sm" 
                                           onclick="return confirm('确定要取消订单吗？')">取消订单</a>
                                    </c:if>
                                    <c:if test="${order.status == 2}">
                                        <a href="${pageContext.request.contextPath}/client/order?action=confirm&orderId=${order.orderId}" 
                                           class="btn btn-success btn-sm"
                                           onclick="return confirm('确认已收到商品？')">确认收货</a>
                                    </c:if>
                                    <c:if test="${order.status == 3}">
                                        <button type="button" class="btn btn-info btn-sm" 
                                                onclick="openReviewModal(${order.orderId}, '${order.orderNo}')">评价商品</button>
                                    </c:if>
                                    <a href="${pageContext.request.contextPath}/client/order?action=detail&orderId=${order.orderId}" 
                                       class="btn btn-outline-primary btn-sm">查看详情</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </c:forEach>
        </c:if>
        
        <c:if test="${orders == null || empty orders}">
            <div class="alert alert-info">
                <h5>暂无订单</h5>
                <p>您还没有任何订单，<a href="${pageContext.request.contextPath}/client/index">去购物</a></p>
            </div>
        </c:if>
        
        <!-- 分页 -->
        <nav aria-label="Page navigation" class="mt-4">
            <div class="row">
                <div class="col-md-12 text-center mb-3">
                    <span class="text-muted">共 <strong>${totalCount}</strong> 件订单，共 <strong>${totalPages}</strong> 页</span>
                </div>
            </div>
            <ul class="pagination justify-content-center">
                <li class="page-item ${page == 1 ? 'disabled' : ''}">
                    <c:choose>
                        <c:when test="${page == 1}">
                            <span class="page-link">上一页</span>
                        </c:when>
                        <c:otherwise>
                            <a class="page-link" href="?page=${page-1}">上一页</a>
                        </c:otherwise>
                    </c:choose>
                </li>
                <li class="page-item">
                    <span class="page-link">第 ${page} 页 / 共 ${totalPages} 页</span>
                </li>
                <li class="page-item ${hasNextPage == false ? 'disabled' : ''}">
                    <c:choose>
                        <c:when test="${hasNextPage == false}">
                            <span class="page-link">下一页</span>
                        </c:when>
                        <c:otherwise>
                            <a class="page-link" href="?page=${page+1}">下一页</a>
                        </c:otherwise>
                    </c:choose>
                </li>
            </ul>
        </nav>
    </div>
    
    <!-- 评价模态框 -->
    <div class="modal fade" id="reviewModal" tabindex="-1" aria-labelledby="reviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reviewModalLabel">商品评价</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="reviewForm">
                        <input type="hidden" id="reviewOrderId" name="orderId">
                        <div class="mb-3">
                            <label class="form-label">订单编号</label>
                            <input type="text" class="form-control" id="reviewOrderNo" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">选择商品</label>
                            <select name="productId" id="reviewProductId" class="form-select" required>
                                <option value="">请选择商品</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">评分</label>
                            <div class="rating-stars" id="reviewRatingStars">
                                <span class="star" data-rating="1">☆</span>
                                <span class="star" data-rating="2">☆</span>
                                <span class="star" data-rating="3">☆</span>
                                <span class="star" data-rating="4">☆</span>
                                <span class="star" data-rating="5">☆</span>
                            </div>
                            <input type="hidden" name="rating" id="reviewRating" value="5" required>
                        </div>
                        <div class="mb-3">
                            <label for="reviewContent" class="form-label">评价内容</label>
                            <textarea class="form-control" id="reviewContent" name="content" rows="5" 
                                      placeholder="请输入您的评价..." required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="reviewImages" class="form-label">评价图片（最多3张）</label>
                            <input type="file" class="form-control" id="reviewImages" name="images" 
                                   accept="image/jpeg,image/jpg,image/png,image/gif,image/bmp,image/webp"
                                   multiple
                                   onchange="previewImages(this)">
                            <small class="form-text text-muted">支持jpg、png、gif、bmp、webp格式，单张图片不超过5MB</small>
                            <div id="imagePreview" class="mt-2"></div>
                        </div>
                        <div class="alert alert-danger d-none" id="reviewError"></div>
                        <div class="alert alert-success d-none" id="reviewSuccess"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitReviewBtn" onclick="submitReview()">提交评价</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <style>
        .rating-stars {
            font-size: 30px;
            color: #ffc107;
            cursor: pointer;
        }
        .rating-stars .star {
            margin-right: 5px;
        }
        .rating-stars .star:hover {
            color: #ffb300;
        }
    </style>
    <script>
        let reviewModal;
        let currentOrderItems = [];
        
        // 页面加载完成后初始化模态框
        document.addEventListener('DOMContentLoaded', function() {
            reviewModal = new bootstrap.Modal(document.getElementById('reviewModal'));
        });
        
        // 打开评价模态框
        function openReviewModal(orderId, orderNo) {
            document.getElementById('reviewOrderId').value = orderId;
            document.getElementById('reviewOrderNo').value = orderNo;
            document.getElementById('reviewProductId').innerHTML = '<option value="">加载中...</option>';
            document.getElementById('reviewContent').value = '';
            document.getElementById('reviewImages').value = '';
            document.getElementById('imagePreview').innerHTML = '';
            selectedImages = []; // 清空选中的图片
            document.getElementById('reviewRating').value = '5';
            document.getElementById('reviewError').classList.add('d-none');
            document.getElementById('reviewSuccess').classList.add('d-none');
            updateStars(5);
            
            // 获取订单商品列表
            fetch('${pageContext.request.contextPath}/client/order?action=json&orderId=' + orderId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.items) {
                        const productSelect = document.getElementById('reviewProductId');
                        productSelect.innerHTML = '<option value="">请选择商品</option>';
                        
                        data.items.forEach(item => {
                            const option = document.createElement('option');
                            option.value = item.productId;
                            option.textContent = item.productName;
                            productSelect.appendChild(option);
                        });
                        
                        // 如果只有一种商品，自动选中
                        if (data.items.length === 1) {
                            productSelect.value = data.items[0].productId;
                        }
                    } else {
                        document.getElementById('reviewProductId').innerHTML = '<option value="">加载失败</option>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('reviewProductId').innerHTML = '<option value="">加载失败</option>';
                });
            
            reviewModal.show();
        }
        
        // 评分星级交互
        const reviewStars = document.querySelectorAll('#reviewRatingStars .star');
        const reviewRatingInput = document.getElementById('reviewRating');
        
        reviewStars.forEach((star, index) => {
            star.addEventListener('click', function() {
                const rating = index + 1;
                reviewRatingInput.value = rating;
                updateStars(rating);
            });
            
            star.addEventListener('mouseenter', function() {
                const rating = index + 1;
                updateStars(rating);
            });
        });
        
        document.getElementById('reviewRatingStars').addEventListener('mouseleave', function() {
            const currentRating = parseInt(reviewRatingInput.value);
            updateStars(currentRating);
        });
        
        function updateStars(rating) {
            reviewStars.forEach((star, index) => {
                if (index < rating) {
                    star.textContent = '★';
                } else {
                    star.textContent = '☆';
                }
            });
        }
        
        // 存储选中的图片文件
        let selectedImages = [];
        
        // 预览图片
        function previewImages(input) {
            const preview = document.getElementById('imagePreview');
            
            // 将新选择的文件添加到数组中
            if (input.files && input.files.length > 0) {
                // 检查总数
                if (selectedImages.length + input.files.length > 3) {
                    alert('最多只能上传3张图片');
                    input.value = '';
                    return;
                }
                
                // 添加新文件到数组
                for (let i = 0; i < input.files.length; i++) {
                    const file = input.files[i];
                    if (file.size > 5 * 1024 * 1024) {
                        alert('图片大小不能超过5MB：' + file.name);
                        continue;
                    }
                    selectedImages.push(file);
                }
            }
            
            // 清空input，避免重复添加
            input.value = '';
            
            // 重新渲染预览
            renderImagePreview();
        }
        
        // 渲染图片预览
        function renderImagePreview() {
            const preview = document.getElementById('imagePreview');
            preview.innerHTML = '';
            
            selectedImages.forEach((file, index) => {
                const container = document.createElement('div');
                container.className = 'image-preview-container';
                
                const img = document.createElement('img');
                const reader = new FileReader();
                reader.onload = function(e) {
                    img.src = e.target.result;
                };
                reader.readAsDataURL(file);
                
                const deleteBtn = document.createElement('span');
                deleteBtn.className = 'delete-btn';
                deleteBtn.innerHTML = '×';
                deleteBtn.title = '删除';
                deleteBtn.onclick = function() {
                    removeImage(index);
                };
                
                container.appendChild(img);
                container.appendChild(deleteBtn);
                preview.appendChild(container);
            });
        }
        
        // 删除图片
        function removeImage(index) {
            selectedImages.splice(index, 1);
            renderImagePreview();
        }
        
        // 提交评价
        function submitReview() {
            const orderId = document.getElementById('reviewOrderId').value;
            const productId = document.getElementById('reviewProductId').value;
            const rating = document.getElementById('reviewRating').value;
            const content = document.getElementById('reviewContent').value.trim();
            const imageInput = document.getElementById('reviewImages');
            
            if (!productId) {
                alert('请选择要评价的商品');
                return;
            }
            
            if (!content) {
                alert('请输入评价内容');
                return;
            }
            
            // 检查图片数量
            if (selectedImages.length > 3) {
                alert('最多只能上传3张图片');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('orderId', orderId);
            formData.append('productId', productId);
            formData.append('rating', rating);
            formData.append('content', content);
            
            // 添加图片文件
            selectedImages.forEach(file => {
                formData.append('images', file);
            });
            
            const submitBtn = document.getElementById('submitReviewBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';
            
            document.getElementById('reviewError').classList.add('d-none');
            document.getElementById('reviewSuccess').classList.add('d-none');
            
            fetch('${pageContext.request.contextPath}/client/review?action=addAjax', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('reviewSuccess').textContent = data.message;
                    document.getElementById('reviewSuccess').classList.remove('d-none');
                    selectedImages = []; // 清空选中的图片
                    setTimeout(function() {
                        reviewModal.hide();
                        location.reload();
                    }, 1500);
                } else {
                    document.getElementById('reviewError').textContent = data.message || '评价失败';
                    document.getElementById('reviewError').classList.remove('d-none');
                    submitBtn.disabled = false;
                    submitBtn.textContent = '提交评价';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('reviewError').textContent = '提交失败，请重试';
                document.getElementById('reviewError').classList.remove('d-none');
                submitBtn.disabled = false;
                submitBtn.textContent = '提交评价';
            });
        }
    </script>
</body>
</html>

